//
//  AppDelegate.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//

import UIKit

@main
class AppDelegate: UIResponder {
    var window: UIWindow?
    // 后台任务标识
    private var backgroundTask: UIBackgroundTaskIdentifier?
    
    private func endBackgroundTask(_ application: UIApplication?) {
        guard let backgroundTask = backgroundTask else {
            return
        }
        application?.endBackgroundTask(backgroundTask)
        self.backgroundTask = UIBackgroundTaskIdentifier.invalid
    }


}

extension AppDelegate: UIApplicationDelegate {
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        LibsManager.shared.setupLibs()
        
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.lxs.hex("#000000")
        window?.rootViewController = NavigationController(rootViewController: LoginViewController())
        window?.makeKeyAndVisible()
//#if DEBUG
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
//            Configs.changeEnvAlert()
//        }
//#else
//        Configs.setupEnv()
//#endif
        
        return true
    }
    
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let devieTokenString = deviceToken.reduce("", { $0 + String(format: "%02x", $1) })
        debugLog("deviceToken: \(devieTokenString)")
    }

    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

    }
    
    /// 强制使用系统键盘类型，排除第三方键盘，比如百度、讯飞
    func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplication.ExtensionPointIdentifier) -> Bool {
        if extensionPointIdentifier.rawValue == "com.apple.keyboard-service" {
            return false
        }
        return true
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        // 延迟程序静止的时间
        DispatchQueue.global().async() {
            // 如果已存在后台任务，先将其设为完成
            self.endBackgroundTask(application)
        }
        
        //如果要后台运行
        backgroundTask = application.beginBackgroundTask(expirationHandler: { [weak self, weak application] () -> Void in
            //如果没有调用endBackgroundTask，时间耗尽时应用程序将被终止
            self?.endBackgroundTask(application)
        })
    }
}
